package Genericity_etc.Exer.Set_etc;

/**
 * @author Jimmy Zhan WORKSTATION
 * @date 2023/3/21 19:06
 * 说明：
 */

public class User implements Comparable{
    String name;
    int age;
    public User(){}

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    // 因为是TreeSet，使用Comparable的compareTo()以及Comparator的compare()比较
    // 因此没有必要重写equals()和hashCode()
//    @Override
//    public boolean equals(Object o) {
//        if (this == o) return true;
//        if (o == null || getClass() != o.getClass()) return false;
//        User user = (User) o;
//        return age == user.age && Objects.equals(name, user.name);
//    }
//
//    @Override
//    public int hashCode() {
//        return Objects.hash(name, age);
//    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    /**
     * 按照年龄从大到小排序，如果年龄相同，则比较姓名：自然排序
     */
    @Override
    public int compareTo(Object o) {
        if (this == o) {
            return 0;
        }
        if (o instanceof User) {
            User us = (User) o;
            int value = this.getAge() - us.getAge();
            if (value != 0) {
                return value;
            }
            return this.getName().compareTo(us.getName());
        }
        throw new RuntimeException("类型不匹配");
    }

}
